package com.linkage.educloud.ah.mvp.presenter.topic;

import android.content.Context;

import com.linkage.educloud.ah.bean.TopicGroupBean;
import com.linkage.educloud.ah.http.Method;
import com.linkage.educloud.ah.http.RequestUtil;
import com.linkage.educloud.ah.mvp.contract.topic.ITopicGroupContract;
import com.linkage.educloud.ah.mvp.contract.topic.ITopicWriterContract;
import com.linkage.educloud.ah.mvp.model.topic.TopicGroupModel;
import com.linkage.educloud.ah.mvp.model.topic.TopicWriterModel;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.BaseSubscriber;
import com.zzhou.common.library.util.ToastShow;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;

/**
 * Created by Mr'Tang on 2018/12/6.
 */

public class TopicWriterPresenter extends ITopicWriterContract.IPresenter<ITopicWriterContract.IView> {
    Context mContext;
    ITopicWriterContract.IModel iModel;

    public TopicWriterPresenter(Context context, ITopicWriterContract.IView iView) {
        super(iView);
        mContext = context;
        iModel = new TopicWriterModel();
    }

    //发布话题帖子
    @Override
    public void pushCard(String topic_id, String picUrls, String title, String input) {
        Observable observable = iModel.request(Method.POST, true, RequestUtil.pushCard(topic_id,picUrls,title,input));
        observable.compose(iView.bindLifecycle())
                .subscribe(new BaseSubscriber<String>() {
                    @Override
                    public void onNext(String s) {
                        ((ITopicGroupContract.IView) iView).stopRefresh();
                        try {
                            JSONObject json = new JSONObject(s);
                            if (json.getInt("ret") == 0) {
                                ((ITopicGroupContract.IView) iView).initRecylerviewDate(TopicGroupBean.parseFromJson(json.optJSONArray("data")));
                            } else {
                                ToastShow.show(mContext, json.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastShow.show(mContext, e.getMessage());
                        }
                    }

                    @Override
                    public void onError(ApiException e) {

                    }
                });
    }
}
